package com.mfc.education.service.email.controller.api;

import com.mfc.education.common.base.result.R;
import com.mfc.education.common.base.result.ResultCodeEnum;
import com.mfc.education.common.base.util.FormUtils;
import com.mfc.education.common.base.util.RandomUtils;
import com.mfc.education.service.base.exception.EduException;
import com.mfc.education.service.email.service.EmailService;
import com.netflix.client.ClientException;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import java.util.concurrent.TimeUnit;

/**
 * @author mfc
 * @since 2021/9/24
 */
 //跨域
@Api(description = "邮箱管理")
@RequestMapping("/api/email")
@RestController
@Slf4j
public class EmailController {

    @Autowired
    private EmailService smsService;

    @Autowired
    private RedisTemplate redisTemplate;


    @GetMapping("send/{qqEmail}")
    public R getCode(@PathVariable String qqEmail) {

        //校验手机号是否合法
        if (StringUtils.isEmpty(qqEmail) || !FormUtils.isEmail(qqEmail)) {
            log.error("请输入正确的qq邮箱号");
            throw new EduException(ResultCodeEnum.LOGIN_EMAIL_ERROR);
        }

        //生成验证码
        String checkCode = RandomUtils.getSixBitRandom();
        //发送验证码
        smsService.send(qqEmail, checkCode);
//                } catch (
//    MessagingException e) {
//            log.error("邮箱发送失败 " + " - code: " + checkCode + ", message: " + e.getMessage());
//            throw new EduException(ResultCodeEnum.EMAIL_SEND_ERROR);
//        }
        //将验证码存入redis缓存
        redisTemplate.opsForValue().set(qqEmail, checkCode, 3, TimeUnit.MINUTES);

        return R.ok().message("邮箱发送成功");
    }


}
